package engine.app;

import engine.input.KeyInput;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.stage.Stage;

public class View extends Canvas {

    public GraphicsContext gc;
    public Engine engine;
    public static KeyInput keyH;

    public View(int screenWidth, int screenHeight) {
        super(screenWidth, screenHeight);
        gc = getGraphicsContext2D();//画笔
        engine = new Engine();
        keyH = new KeyInput();
    }

    public void onUpdate() {
    }

    public void onStart() {
    }

    public void onStop() {
    }

    public void initEngine(Stage stage) {
        engine.onStart = () -> {
            onStart();
            keyH.install(stage);
        };
        engine.onUpdate = () -> {
            onUpdate();
            keyH.refresh();
        };
        engine.onStop = () -> {
            keyH.uninstall(stage);
            onStop();
        };
        //注册窗口焦点监听器
        stage.focusedProperty().addListener((o, ov, nv) -> {
            if (nv) {
                engine.start();//当窗口获得焦点时启动引擎
            } else {
                engine.stop();//当窗口失去焦点时停止引擎
            }
        });
    }

}
